package com.benyq.networkprogramme

import android.app.Activity
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.benyq.networkprogramme.base.adapter.BenyqBaseAdapter
import com.benyq.networkprogramme.base.bean.FileBean
import com.benyq.networkprogramme.base.bean.LocalFileBean
import com.benyq.networkprogramme.ftp.FtpHelper
import kotlinx.android.synthetic.main.fragment_file.*
import org.apache.commons.net.ftp.FTPFile
import java.io.File
import java.io.FileFilter
import java.lang.ref.WeakReference
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * @author benyq
 * @date 18-9-27 10:07
 * @E-mail： 1520063035@qq.com
 * @description
 */
class FileFragment: Fragment() {

    private var currentType = -1
    val fileAdapter by lazy { FtpFileAdapter(activity!!) }
    val localFileAdapter by lazy { LocalFileAdapter(activity!!) }
    private var executorService: ExecutorService = Executors.newSingleThreadExecutor()
    private var hasLoadData = false
    private val myHandler = MyHandler(this)


    companion object {
        val typeUpload = 0
        val typeDown = 1

        fun getInstance(type: Int): FileFragment{
            val fragment = FileFragment()
            val bundle = Bundle()
            bundle.putInt("type", type)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        currentType = arguments?.getInt("type") ?: -1
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_file, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        if (!hasLoadData) {
            lazyLoad()
            hasLoadData = true
        }
    }

    override fun onDestroy() {
        myHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    private fun lazyLoad(){
        executorService.execute {
            when(currentType){
                typeDown -> {
                    executorService.execute {
                        FtpHelper.openConnect()
                        val files = FtpHelper.listFiles("./ftp")
                        Log.e("susan", "num${files.size}")
                        files.forEach {
                            Log.e("susan", it.name)
                        }
                        val fileBeen = files.map {
                            FileBean(false, it)
                        }
                        Log.e("susan", "fileBean${fileBeen.size}")
                        val msg = Message()
                        msg.what = 1
                        msg.obj = fileBeen
                        myHandler.sendMessage(msg)
                    }
                }
                typeUpload -> {
//                    this@FileFragment.activity!!.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
//                            .absolutePath
//                    val locaFile = Environment.getExternalStorageDirectory().absolutePath
                    val locaFile = this@FileFragment.activity!!.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).absolutePath
                    val file = File(locaFile)
                    val files = listOf(*file.listFiles(FileFilter {
                        it.isFile
                    }))
                    val fileBeen = files.map {
                        LocalFileBean(false, it)
                    }
                    localFileAdapter.addNewData(fileBeen)
                }
            }
        }
    }

    private fun initView(){
        rvFile.layoutManager = LinearLayoutManager(activity)

        fileAdapter.setOnItemClickListener(object: BenyqBaseAdapter.OnItemClickListener{
            override fun onItemClick(view: View, position: Int) {
                fileAdapter.datas[position].check = !fileAdapter.datas[position].check
                fileAdapter.notifyItemChanged(position)
            }

        })

        localFileAdapter.setOnItemClickListener(object: BenyqBaseAdapter.OnItemClickListener{
            override fun onItemClick(view: View, position: Int) {
                localFileAdapter.datas[position].check = !localFileAdapter.datas[position].check
                localFileAdapter.notifyItemChanged(position)
            }

        })

        when(currentType){
            typeUpload -> {
                tvTitle.text = "上传"
                rvFile.adapter = localFileAdapter
            }
            typeDown -> {
                tvTitle.text = "下载"
                rvFile.adapter = fileAdapter
            }
        }
        btnTransfer.setOnClickListener{
            when(currentType){
                typeUpload -> {
                    val file = localFileAdapter.datas.filter { it.check }[0]
                    executorService.execute{
                        Log.e("susan", "upload---${file.file.absolutePath}")
                        val b = FtpHelper.uploadFile(file.file)
                        Log.e("susan", "upload---$b")
                    }
                }
                typeDown -> {
                    val file = fileAdapter.datas.filter { it.check }[0]
                    executorService.execute{
                        val localFileName =  this@FileFragment.activity!!.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                                .absolutePath + File.separator + file.ftpFile.name
                        Log.e("susan", localFileName)
                        val localFile = File(localFileName)
                        val b = FtpHelper.downFile(localFile, file.ftpFile)
                        Log.e("susan", "susu---$b")
                    }
                }
            }

        }
    }

    class MyHandler(fragment: FileFragment): Handler(){

        private var mFragment: WeakReference<FileFragment> = WeakReference(fragment)

        override fun handleMessage(msg: Message) {
            when(msg.what){
                1 -> {
                    val files = msg.obj as List<FileBean>

                    mFragment.get()?.run {
                        Log.e("susan", "fileBesadasdasdasan${files.size}")
                        fileAdapter.addNewData(files)
                    }
                }
            }

        }
    }
}